#!/usr/bin/env python3
# HFT系统性能分析工具

import json
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
import numpy as np
import argparse

class PerformanceAnalyzer:
    def __init__(self, log_file='logs/hft_performance.log'):
        self.log_file = log_file
        self.data = None
        self.report_dir = 'reports/performance'
        os.makedirs(self.report_dir, exist_ok=True)
        
    def load_data(self):
        """加载性能日志数据"""
        records = []
        with open(self.log_file) as f:
            for line in f:
                try:
                    record = json.loads(line.strip())
                    records.append(record)
                except json.JSONDecodeError:
                    continue
        
        self.data = pd.DataFrame(records)
        
        # 转换时间戳
        if 'timestamp' in self.data:
            self.data['timestamp'] = pd.to_datetime(self.data['timestamp'])
        
        return len(records)
    
    def analyze_latency(self):
        """分析订单执行延迟"""
        if 'latency_ms' not in self.data:
            print("警告: 日志中缺少延迟数据")
            return
        
        latency = self.data['latency_ms']
        
        # 基本统计
        stats = {
            'count': len(latency),
            'mean': np.mean(latency),
            'min': np.min(latency),
            'max': np.max(latency),
            'std': np.std(latency),
            'p50': np.percentile(latency, 50),
            'p90': np.percentile(latency, 90),
            'p99': np.percentile(latency, 99)
        }
        
        # 保存统计结果
        with open(f'{self.report_dir}/latency_stats.json', 'w') as f:
            json.dump(stats, f, indent=2)
        
        # 生成图表
        plt.figure(figsize=(12, 6))
        sns.histplot(latency, bins=50, kde=True)
        plt.title('Order Execution Latency Distribution')
        plt.xlabel('Latency (ms)')
        plt.ylabel('Count')
        plt.savefig(f'{self.report_dir}/latency_distribution.png')
        plt.close()
        
        return stats
    
    def analyze_strategy_performance(self):
        """分析策略表现"""
        if 'strategy' not in self.data or 'pnl' not in self.data:
            print("警告: 日志中缺少策略表现数据")
            return
        
        # 按策略分组统计
        strategy_stats = self.data.groupby('strategy')['pnl'].agg([
            'count', 'sum', 'mean', 'std', 'min', 'max'
        ]).reset_index()
        
        # 保存统计结果
        strategy_stats.to_csv(f'{self.report_dir}/strategy_performance.csv', index=False)
        
        # 生成图表
        plt.figure(figsize=(12, 6))
        sns.barplot(x='strategy', y='sum', data=strategy_stats)
        plt.title('Strategy Performance (Total PnL)')
        plt.xlabel('Strategy')
        plt.ylabel('Total PnL')
        plt.savefig(f'{self.report_dir}/strategy_pnl.png')
        plt.close()
        
        return strategy_stats
    
    def analyze_system_metrics(self):
        """分析系统指标"""
        required_metrics = ['cpu_usage', 'memory_usage', 'network_usage']
        missing = [m for m in required_metrics if m not in self.data]
        
        if missing:
            print(f"警告: 日志中缺少系统指标数据: {', '.join(missing)}")
            return
        
        # 时间序列分析
        metrics = self.data[['timestamp'] + required_metrics]
        metrics.set_index('timestamp', inplace=True)
        
        # 生成图表
        plt.figure(figsize=(12, 8))
        for i, metric in enumerate(required_metrics, 1):
            plt.subplot(len(required_metrics), 1, i)
            plt.plot(metrics.index, metrics[metric])
            plt.title(f'{metric.replace("_", " ").title()} Over Time')
            plt.xlabel('Time')
            plt.ylabel(metric.replace("_", " ").title())
        
        plt.tight_layout()
        plt.savefig(f'{self.report_dir}/system_metrics.png')
        plt.close()
        
        return metrics.describe()
    
    def generate_report(self):
        """生成综合性能报告"""
        report = {
            'timestamp': datetime.now().isoformat(),
            'log_file': self.log_file,
            'record_count': len(self.data),
            'latency': self.analyze_latency(),
            'strategy_performance': self.analyze_strategy_performance(),
            'system_metrics': self.analyze_system_metrics()
        }
        
        with open(f'{self.report_dir}/performance_report.json', 'w') as f:
            json.dump(report, f, indent=2)
        
        print(f"性能报告已生成到: {self.report_dir}")
        return report

def main():
    parser = argparse.ArgumentParser(description='HFT系统性能分析工具')
    parser.add_argument('--log', default='logs/hft_performance.log', help='性能日志文件路径')
    args = parser.parse_args()
    
    analyzer = PerformanceAnalyzer(args.log)
    
    try:
        record_count = analyzer.load_data()
        print(f"已加载 {record_count} 条性能记录")
        
        report = analyzer.generate_report()
        print("分析完成")
    except Exception as e:
        print(f"错误: {e}")
        exit(1)

if __name__ == '__main__':
    import os
    main()